export default {
	namespaced: true,
	state() {
		return {
			// 购物车的数组，用来存储购物车中每个商品的信息对象
			// 每个商品的信息对象，都包含如下 6 个属性：
			// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
			cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
		}
	},
	mutations: {
		// 添加到购物车
		addToCart(state, goods) {
			const findRet = state.cart.find(e => e.goods_id === goods.goods_id)
			if (findRet)
				findRet.goods_count += 1
			else
				state.cart.unshift(goods)

			this.commit('cart/saveToStorage')
		},
		// 持久化存储到本地
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		//商品选中状态
		updateGoodsState(state, goods) {
			const findRet = state.cart.find(e => e.goods_id === goods.goods_id)
			if (findRet) {
				findRet.goods_state = goods.goods_state
				this.commit('cart/saveToStorage')
			}
		},
		// 持久化商品数量
		updateGoodsCount(state, goods) {
			const findRet = state.cart.find(e => e.goods_id === goods.goods_id)
			if (findRet) {
				findRet.goods_count = goods.goods_count
				this.commit('cart/saveToStorage')
			}
		},
		removeGoodsById(state, goods) {
			state.cart = state.cart.filter(e => e.goods_id !== goods.goods_id)
			this.commit('cart/saveToStorage')
		},
		updateAllGoodsState(state, newState) {
			state.cart.forEach(e => e.goods_state = newState)
			this.commit('cart/saveToStorage')
		}
	},
	getters: {
		total(state) {
			let num = 0
			state.cart.forEach(e => {
				num += e.goods_count
			})
			return num
		},
		// 结算商品的总数量
		checkedCount(state) {
			return state.cart.filter(e => e.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},
		checkedGoodsAmount(state) {
			return state.cart.filter(e => e.goods_state)
				.reduce((total, item) => total += item.goods_count * item.goods_price, 0)
				.toFixed(2)
		}
	},

}
